package com.hnd.springframework.beans.factory.support.InstantiationStrategyImpl;

import com.hnd.springframework.beans.BeansException;
import com.hnd.springframework.beans.factory.config.BeanDefinition;
import com.hnd.springframework.beans.factory.support.InstantiationStrategy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, Constructor ctor, String beanName, Object... args) {
        Class clazz = beanDefinition.getBeanClass();
        Object bean = null;
        try {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(clazz);
            enhancer.setCallback(new NoOp() {
                @Override
                public int hashCode() {
                    System.out.println("巴拉巴拉小魔仙");
                    return super.hashCode();
                }
            });
            if (ctor == null) {
                return enhancer.create();
            }
            bean = enhancer.create(ctor.getParameterTypes(), args);
        } catch (RuntimeException e) {
            throw new BeansException("bean 实例化失败", e);
        }
        return bean;
    }
}
